package com.authine.cloudpivot.ext.applicationservice;


import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.dto.SingleResponse;
import com.authine.cloudpivot.ext.dto.HistogramDataDto;
import com.authine.cloudpivot.ext.dto.HistogramDataVo;
import com.authine.cloudpivot.ext.dto.kanban.KanbanDto;
import com.authine.cloudpivot.ext.dto.kanban.OperationKanbanQueryDto;
import com.authine.cloudpivot.ext.enums.ServiceEnumType;
import com.authine.cloudpivot.ext.utils.KanbanJdbcUtil;
import com.authine.cloudpivot.ext.utils.PmUtil;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.google.common.collect.Lists;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

@Slf4j
@Path("OperationKanBanService")
public class OperationKanBanService extends ApplicationService {

    /**
     * 参与报价率
     */
    public static final String CANYURATE = "CANYU_BAOJIA_RATE";
    /**
     * 询价定标率
     */
    public static final String INQUIRYDINGBIAORATE = "INQUIRY_DINGBIAO_RATE";

    /**
     * 询价下单率
     */
    public static final String INQUIRY_ORDER_RATE = "INQUIRY_ORDER_RATE";

    /**
     * 报价定标率
     */
    public static final String BAOJIA_DINGBIAO_RATE = "BAOJIA_DINGBIAO_RATE";


    /**
     * 报价下单率
     */
    public static final String BAOJIA_ORDER_RATE = "BAOJIA_ORDER_RATE";


    /**
     * 定标下单率
     */
    public static final String DINGBIAO_ORDER_RATE = "DINGBIAO_ORDER_RATE";


    @Path("histogramData")
    @POST
    @Operation(summary = "首页-柱状图询价定标数据",tags = CUSTOM_SERVICE)
    public SingleResponse histogramData(HistogramDataDto histogramDataDto){

        Map<String,Object> param = new LinkedHashMap<>();
        Map<String,Object> dataMap = new LinkedHashMap<>();
        List<String> dataList = Lists.newArrayList();
        int days = PmUtil.differentDaysByMillisecond(histogramDataDto.getStartTime(), histogramDataDto.getEndTime());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(histogramDataDto.getStartTime());
        calendar.add(Calendar.DATE,-1);
        for (int i = 0; i<=days; i++){
            calendar.add(Calendar.DATE,1);
            String dateFormatStrMMdd = PmUtil.dateFormatStrMMdd(calendar.getTime());
            param.put(dateFormatStrMMdd,"");
            dataList.add(dateFormatStrMMdd);
        }
        //histogramDataDto.setOrgName("牧原测试组织");
        if(StringUtils.isEmpty(histogramDataDto.getOrgName())) {
            histogramDataDto.setOrgName(Objects.requireNonNull(PmUtil.getOrgOrganization("")).getName());
        }

        //查询指定时间段内询价数
        List<HistogramDataVo> inquiryKanbas = KanbanJdbcUtil.queryInquiryByTime(histogramDataDto);
        Map<String, HistogramDataVo> inquiryKanbasMap = inquiryKanbas.stream().collect(Collectors.toMap(HistogramDataVo::getTime, Function.identity()));

        //查询指定时间段内定标数
        List<HistogramDataVo> dingbiaoDtos = KanbanJdbcUtil.queryDingbiaoByTime(histogramDataDto);
        Map<String, HistogramDataVo> dingbiaosMap = dingbiaoDtos.stream().collect(Collectors.toMap(HistogramDataVo::getTime, Function.identity()));

        List<Integer> inquiryCountList = Lists.newArrayList();
        List<Integer> dingbiaoCountList = Lists.newArrayList();
        for (String key:param.keySet()){
            HistogramDataVo inquiry = inquiryKanbasMap.get(key);
            if(Objects.isNull(inquiry)){
                inquiryCountList.add(0);
            }else {
                inquiryCountList.add(inquiry.getInquiryCount());
            }
            HistogramDataVo dingbiao = dingbiaosMap.get(key);
            if(Objects.isNull(dingbiao)){
                dingbiaoCountList.add(0);
            }else {
                dingbiaoCountList.add(dingbiao.getDingbiaoCount());
            }
        }
        dataMap.put("length",days);
        dataMap.put("inquiry_num",inquiryCountList);
        dataMap.put("picketage_num",dingbiaoCountList);
        dataMap.put("data",dataList);
        return SingleResponse.of(dataMap);
    }







    @Path("queryKanban")
    @POST
    @Operation(summary = "运营看板",tags = CUSTOM_SERVICE)
    public SingleResponse queryKanban(@Parameter OperationKanbanQueryDto kanban){

        Map<Object,Object> param = new HashMap<>();

        //查询今日询价 昨日询价  询价总次数
        List<KanbanDto> inquiryKanbas = KanbanJdbcUtil.queryInquiryByTime(kanban);
        param = KanbanJdbcUtil.convertParamenter(param,inquiryKanbas, ServiceEnumType.INQUIRY.getId(),kanban);

        //今日报价数，昨日报价数量，报价总次数
        List<KanbanDto> quotationKanbanDtos = KanbanJdbcUtil.queryQuotationByTime(kanban);
        param = KanbanJdbcUtil.convertParamenter(param,quotationKanbanDtos,ServiceEnumType.QUOTATION.getId(),kanban);

        //定标
        List<KanbanDto> dingbiaoDtos = KanbanJdbcUtil.queryDingbiaoByTime(kanban);
        param = KanbanJdbcUtil.convertParamenter(param,dingbiaoDtos,ServiceEnumType.DINGBIAO.getId(),kanban);


        //订单金额
        List<KanbanDto> orderMoneys  = KanbanJdbcUtil.queryOrderMoneyByTime(kanban);
        param = KanbanJdbcUtil.convertParamenter(param,orderMoneys,ServiceEnumType.ORDERMONEY.getId(),kanban);


        //订单数量
        List<KanbanDto> orderNumbers = KanbanJdbcUtil.queryOrderNumberyByTime(kanban);
        param = KanbanJdbcUtil.convertParamenter(param,orderNumbers,ServiceEnumType.ORDERNUMBER.getId(),kanban);


        //订单商品数量
        List<KanbanDto> orderGoodNumbers = KanbanJdbcUtil.queryOrderGoodNumberyByTime(kanban);
        param = KanbanJdbcUtil.convertParamenter(param,orderGoodNumbers,ServiceEnumType.ORDERGOODNUMBER.getId(),kanban);


        //订单退款金额
        List<KanbanDto> orderGoodsReturn = KanbanJdbcUtil.queryOrderGoodsReturn(kanban);
        param = KanbanJdbcUtil.convertParamenter(param,orderGoodsReturn,ServiceEnumType.ORDERGOODRETURN.getId(),kanban);

        return SingleResponse.of(param);
    }


    @Path("queryKanbanRate")
    @POST
    @Operation(summary = "运营看板",tags = CUSTOM_SERVICE)
    public SingleResponse queryKanbanRate(@Parameter OperationKanbanQueryDto kanban){
        Map<String,Object> param = new HashMap<>();
        //参与报价次数
        Integer canyuBaojiacount = KanbanJdbcUtil.queryCanyuBaojia(kanban);
        //参与询价次数
        List<KanbanDto> inquiryKanbas = KanbanJdbcUtil.queryInquiryByTime(kanban);

        //参与报价率
        Integer inquiryCount = calculateRate((float) canyuBaojiacount, inquiryKanbas);
        extractRate(param, canyuBaojiacount, inquiryCount,CANYURATE);

        //询价定标率
        Integer dingbiaoNum = KanbanJdbcUtil.queryDingbiaoNum(kanban);
        extractRate(param, dingbiaoNum, inquiryCount,INQUIRYDINGBIAORATE);

        //询价下单率

        // 查询已报价的询价
        Integer xiadanNum = KanbanJdbcUtil.queryXunjiaxiadan(kanban);
        extractRate(param, xiadanNum, inquiryCount,INQUIRY_ORDER_RATE);

        //报价定标率

        //已报价的询价
        Integer quotationInquiryNum = KanbanJdbcUtil.queryQuotationInquiryNum(kanban);
        extractRate(param, dingbiaoNum, quotationInquiryNum,BAOJIA_DINGBIAO_RATE);
        //报价下单率
        extractRate(param, xiadanNum, quotationInquiryNum,BAOJIA_ORDER_RATE);
        //定标下单率
        extractRate(param, xiadanNum, dingbiaoNum,DINGBIAO_ORDER_RATE);
        return SingleResponse.of(param);
    }



    private void extractRate(Map<String, Object> param, Integer num, Integer total,String type) {
        if (total == null || total == 0){
            param.put(type,0);
            return;
        }
        double v = new BigDecimal((float) num * 100 / total).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        param.put(type,v);
    }

    public Integer calculateRate(float canyuBaojiacount, List<KanbanDto> inquiryKanbas) {
        AtomicReference<Integer> inquiryNum = new AtomicReference<>(0);
        if (inquiryKanbas != null && inquiryKanbas.size() > 0){
            inquiryKanbas.forEach(item->{
                String time = item.getTime();
                if (KanbanJdbcUtil.ALL.equals(time)){
                    String count = item.getCount();
                    if(StringUtils.isNotBlank(count)){
                        inquiryNum.set(Integer.parseInt(count));

                    }else{
                        inquiryNum.set(0);
                    }

                }

            });
        }
        return inquiryNum.get();

    }

    @Path("queryKanBanOrgInfo")
    @POST
    @Operation(summary = "查询组织机构",tags = CUSTOM_SERVICE)
    public SingleResponse queryKanBanOrgInfo(){
        List<Map<String, Object>> maps = KanbanJdbcUtil.queryKanBanOrgInfo();
        return SingleResponse.of(maps);
    }
}
